package org.kernely.ui.settings;

import java.util.Set;

import org.apache.shiro.crypto.hash.Sha256Hash;
import org.kernely.security.dao.UserDAO;
import org.kernely.security.dao.UserDetailsDAO;
import org.kernely.security.persistence.User;
import org.kernely.security.persistence.UserDetails;
import org.kernely.ui.MainApplication;
import org.kernely.ui.home.KernelyHomeView;
import org.kernely.ui.mvp.KernelyPresenter;
import org.kernely.ui.mvp.ViewIdentifier;
import org.kernely.ui.services.KernelyUIBundle;
import org.kernely.ui.utils.KernelyNotification;

import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;

/**
 *	Presenter of KernelySettingsView, managing user settings.
 */
public class KernelySettingsPresenter extends KernelyPresenter<KernelySettingsView> {

	/**
	 * @see KernelyPresenter#bind()
	 */
	@Override
	public final void bind() {
		this.view.getSavePasswordButton().addListener(new ClickListener(){

			/**
			 * @see com.vaadin.ui.Button.ClickListener#buttonClick(com.vaadin.ui.Button.ClickEvent)
			 */
			public void buttonClick(ClickEvent event) {
				savePasswordProcess();
			}

		});
		
		this.view.getResetButton().addListener(new ClickListener() {
			
			/**
			 * @see com.vaadin.ui.Button.ClickListener#buttonClick(com.vaadin.ui.Button.ClickEvent)
			 */
			public void buttonClick(ClickEvent event) {
				resetDefaultHomePage();
			}
		});
		
		// Kernely default page
		ViewIdentifier defaultPage = new ViewIdentifier("Kernely default home page",(KernelyHomeView.class).toString(),MainApplication.getBundleName());
		this.view.getHomePagesBox().addItem(defaultPage);
		this.view.getHomePagesBox().setItemCaption(defaultPage,"Kernely default home page");
		this.view.getHomePagesBox().setValue(defaultPage);

		UserDetailsDAO uddao = UserDetailsDAO.getInstance();
		UserDetails details = uddao.getUserDetails(MainApplication.getSecurityService().getCurrentUser());
		String currentView = details.getHomepageview();
		String currentBundle = details.getHomepagebundle();
		
		// All other pages
		for (KernelyUIBundle bundle : MainApplication.getKernelyUIBundleService().getUIBundles()){
			// If the bundle provides home pages
			Set<ViewIdentifier> pages = bundle.getFrontPages();
			if(pages != null){
				for (ViewIdentifier viewIdentifier : pages){
					this.view.getHomePagesBox().addItem(viewIdentifier);
					this.view.getHomePagesBox().setItemCaption(viewIdentifier,
							viewIdentifier.getViewName() + " ("+ bundle.getName()+")");
					if (viewIdentifier.getViewClass().equals(currentView) && viewIdentifier.getViewBundleName().equals(currentBundle)){
						this.view.getHomePagesBox().setValue(viewIdentifier);
					}
					
				}
			}

		}
		this.view.getApplyButton().addListener(new ClickListener(){
			/**
			 * Called when a ClickEvent is fired
			 */
			public void buttonClick (Button.ClickEvent event) {
				UserDetailsDAO uddao = UserDetailsDAO.getInstance();
				UserDetails details = uddao.getUserDetails(MainApplication.getSecurityService().getCurrentUser());
				ViewIdentifier identifier = (ViewIdentifier) view.getHomePagesBox().getValue();
				details.setHomepagebundle(identifier.getViewBundleName());
				details.setHomepageview(identifier.getViewClass());
				uddao.updateUserDetails(details);

				view.getWindow().showNotification(new KernelyNotification("The default page has been changed to " + identifier.getViewName()+".",KernelyNotification.INFO_ICON));
			}
		});
	}


	private void savePasswordProcess() {

		// We check the validity of user's inputs
		try {
			User u = MainApplication.getSecurityService().getCurrentUser();
			UserDAO udao = UserDAO.getInstance();
			UserDetailsDAO uddao = new UserDetailsDAO();

			//Check if the fields are empty or not
			view.getOldPasswordField().validate();
			view.getNewPasswordField().validate();
			view.getConfirmPasswordField().validate();

			//Check the new and confirm password are the same
			if (! view.getNewPasswordField().toString().equals(view.getConfirmPasswordField().toString())){
				throw new InvalidValueException("You have entered different password in the New and Confirm fields.");
			}

			//Check if the user entered the valid old password
			String password = (new Sha256Hash(view.getOldPasswordField().getValue().toString())).toString();
			String userPassword = u.getPassword();
			if (userPassword.equals(password)){
				u.setPassword((new Sha256Hash(view.getNewPasswordField().getValue().toString())).toString());
				udao.update(u);
			} else {				
				throw new InvalidValueException("You entered a wrong password.");
			}
			view.getWindow().showNotification(new KernelyNotification("Password successfully changed.", KernelyNotification.INFO_ICON));
		}
		catch (InvalidValueException e){
			//Log the failure on screen, to give feedback to the user
			KernelyNotification n = new KernelyNotification(e.getMessage(), KernelyNotification.ERROR_ICON);
			view.getWindow().showNotification(n);
		}
	}
	
	private void resetDefaultHomePage(){
		UserDetailsDAO uddao = UserDetailsDAO.getInstance();
		UserDetails details = uddao.getUserDetails(MainApplication.getSecurityService().getCurrentUser());
		details.setHomepagebundle(null);
		details.setHomepageview(null);
		uddao.updateUserDetails(details);

		view.getWindow().showNotification(new KernelyNotification("The home page is back to default.",KernelyNotification.INFO_ICON));

	}
}
